package com.feishi.core.util.serialize.kryo;

import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;

import java.io.*;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by caixq on 4/27 027.
 */
public class SerializeKryoUtil {

    private static Kryo kryo = new Kryo();
    private static Set<Class> classes=new HashSet<>();
    static {
        kryo.setReferences(false);
    }

    public static <T> T readObject(byte[] bytes,Class<T> T) throws IOException, ClassNotFoundException {
        return readObject(new ByteArrayInputStream(bytes),T);
    }
    public static <T> T readObject(InputStream in, Class<T> t) throws IOException, ClassNotFoundException {
        register(t);
        Input input = new Input(in);
        T object = kryo.readObject(input, t);
        input.close();
        return object;
    }

    private static <T> void register(Class<T> t) {
        if(classes.contains(t)){
            return;
        }
        kryo.register(t, classes.size());
        classes.add(t);
    }

    public static <T> void writeObject(OutputStream out, T t ) throws IOException{
        register(t.getClass());
        Output output=new Output(out);
        kryo.writeObject(output, t);
        output.flush();
        out.flush();
    }
    public static <T> byte[] getBytes(T t ) throws IOException{
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        writeObject(out,t);
        out.flush();
        byte[] arr = out.toByteArray();
        out.close();
        return arr;
    }
}
